<!-- eslint-disable vue/valid-v-for -->
<template>
  <el-row :gutter="20">
    <!-- 左侧标签树 -->
    <el-col :span="9" :xs="24">
      <ContentWrap class="h-1/1">
        <BiaoQianTree
          ref="biaoQianTreeRef"
          @success="getRuleList"
          @changeRuleQueryParam="changeRuleQueryParam"
        />
      </ContentWrap>
    </el-col>
    <el-col :span="15" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-button @click="handleQuery">导入</el-button>
        <el-button @click="createLabel">生成</el-button>
        <el-button @click="openTemplate">打开模版</el-button>
        <el-button @click="closeTemplate">关闭模版</el-button>
        <el-button @click="merge">合并</el-button>
        <el-button @click="split">拆分</el-button>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-model="queryParams.ruleName"
              placeholder="请输入规则名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"> <Icon icon="ep:search" />搜索 </el-button>
            <el-button type="primary" plain @click="openForm('create')">
              <Icon icon="ep:plus" /> 添加规则
            </el-button>
            <el-button
              type="primary"
              plain
              @click="deleteIds()"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> 批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" label="id" align="center" key="id" prop="id" />
          <el-table-column
            label="规则名称"
            align="center"
            prop="ruleName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button type="primary" link @click="openForm('update', scope.row.id)">
                  <!-- <Icon icon="ep:edit" />修改 -->
                  修改
                </el-button>
                <el-button type="primary" link @click="handleDelete(scope.row.id)">
                  <!-- <Icon icon="ep:delete" />删除 -->
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getRuleList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 规则添加或修改规则 -->
  <RuleForm ref="ruleFormRef" @success="getRuleList" />
  <!-- 打开顶级标签模版 -->
  <Tag ref="tagRef" @success="getRuleList" @getTreeList="getTreeList" />

  <MergeForm ref="mergeFormRef" />
  <!-- 点击拆分操作 -->
  <SplitForm ref="splitFormRef" />
</template>
<script lang="ts" setup>
// import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

import * as BiaoqianApi from '@/api/system/biaoqian'
import RuleForm from './RuleForm.vue'
import Tag from './Tag.vue'
import MergeForm from './MergeForm.vue'
import BiaoQianTree from './BiaoQianTree.vue'
import { ElTable } from 'element-plus'
import SplitForm from './SplitForm.vue'

defineOptions({ name: 'SystemUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const isShow = ref(true)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  ruleName: '',
  labelId: ''
})
// const idList = ref([])

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const queryFormRef = ref() // 搜索的表单

const deleteIds = async () => {
  // 批量删除 获取id数组
  try {
    if (multipleSelection.value.length == 0) return message.warning('请选择要删除的规则')
    const ids = multipleSelection.value.map((multiple) => multiple.id)
    //确认删除
    await message.delConfirm()
    await BiaoqianApi.deleteRuleList(ids)
    message.success(t('common.delSuccess'))
    await getRuleList()
  } catch {}
}

const biaoQianTreeRef = ref(null)
var tamplateids = {}

const getTreeList = (listBiaoqianApiParams) => {
  tamplateids = listBiaoqianApiParams.nameList
  tamplateids = tamplateids.split(';')

  console.log('进入了父组件 index.vue 中')

  //父组件访问子组件 BiaoQianTree 的实例
  if (biaoQianTreeRef.value) biaoQianTreeRef.value.getLabelTree(listBiaoqianApiParams)
  console.log('---在父组件 index.vue中调用了 BiaoQianTree.vue中getLabelTree方法----')
  isShow.value = false
}

/** 查询规则列表 */
const getRuleList = async () => {
  loading.value = true
  try {
    const data = await BiaoqianApi.getRulePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getRuleList()
}

/** 当标签树形结构点击时 触发(对规则的查询条件) 对规则列表进行重新查询 */
const changeRuleQueryParam = async (id: string) => {
  queryParams.labelId = id
  queryParams.pageNo = 1
  queryParams.pageSize = 10
}
/** 规则 添加/修改操作 */
const ruleFormRef = ref()

/**  id?:代表可选操作   */
const openForm = (type: string, id?: number) => {
  /**添加规则操作 展示左侧树形结构当前节点  */
  console.log('当前树形结构id为:', biaoQianTreeRef.value.handleNodeClickData['parentId'])
  if (!biaoQianTreeRef.value.handleNodeClickData && type == 'create') {
    return message.info('当前标签不能添加规则')
  }
  if (biaoQianTreeRef.value.handleNodeClickData['parentId'] === -1 && type == 'create') {
    return message.info('当前标签不能添加规则')
  }
  if (biaoQianTreeRef.value.handleNodeClickData['parentId'] === 0 && type == 'create') {
    return message.info('当前标签不能添加规则')
  } else {
    isShow.value = false
  }
  if (isShow.value) message.info('当前标签不能添加规则')
  else {
    ruleFormRef.value.open(type, id, biaoQianTreeRef.value.handleNodeClickData)
  }
}

/**打开标签模版操作 */
const tagRef = ref()
const openTemplate = () => {
  tagRef.value.open()
}
/** 关闭指定标签操作 */
const closeTemplate = () => {
  if (!biaoQianTreeRef.value.handleNodeClickData) {
    return message.info('当前模版不能关闭,请重新选择模版')
  }
  // 判断当前节点是不是最顶级节点
  if (biaoQianTreeRef.value.handleNodeClickData['id'] == '0') {
    return message.info('当前模版不能关闭,请重新选择模版')
  } else {
    // 查看是否是顶级节点
    if (biaoQianTreeRef.value.handleNodeClickData['parentId'] != '0') {
      return message.info('当前模版不能关闭,请重新选择模版')
    } else {
      // 获取要关闭的标识
      const tamplateId = biaoQianTreeRef.value.handleNodeClickData['tamplateid']
      console.log(tamplateids)
      console.log(tamplateId)

      let index = tamplateids.indexOf(tamplateId)
      console.log(index)
      if (index > -1) {
        tamplateids.splice(index, 1)
      }

      const newtamplateidArray = tamplateids.join(';')
      biaoQianTreeRef.value.listBiaoqianApiParams = {
        nameList: newtamplateidArray,
        labelname: ''
      }
      console.log(
        ' biaoQianTreeRef.value.listBiaoqianApiParams',
        biaoQianTreeRef.value.listBiaoqianApiParams
      )
      biaoQianTreeRef.value.getLabelTree(biaoQianTreeRef.value.listBiaoqianApiParams)
    }
  }
}
/**合并操作 */
const mergeFormRef = ref()
const merge = () => {
  mergeFormRef.value.open()
}
/**拆分操作 */
const splitFormRef = ref()

const split = () => {
  if (!biaoQianTreeRef.value.handleNodeClickData) return message.info('请选择要拆分的标签')
  console.log(biaoQianTreeRef.value.handleNodeClickData['id'], ':拆分模版id为')
  console.log(biaoQianTreeRef.value.handleNodeClickData['tamplateid'], ':拆分模版标识id')
  splitFormRef.value.open(
    biaoQianTreeRef.value.handleNodeClickData['id'],
    biaoQianTreeRef.value.handleNodeClickData['tamplateid']
  )
}
/**生成标签操作 */
const createLabel = () => {
  alert('---------------')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BiaoqianApi.deleteRule(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getRuleList()
  } catch {}
}

/** 初始化 */
onMounted(() => {
  getRuleList()
})
</script>
